//
//  ViewController.m
//  JuSocket
//
//  Created by Juvid on 2018/3/9.
//  Copyright © 2018年 Juvid. All rights reserved.
//

#import "ViewController.h"
#import "WHPingTester.h"
@interface ViewController ()<UITextFieldDelegate,NSStreamDelegate,WHPingDelegate>{
    NSInputStream *_inputStream;//对应输入流
    NSOutputStream *_outputStream;//对应输出流
}
@property(nonatomic, strong) WHPingTester* pingTester;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *ju_btnLogin;
@property (weak, nonatomic) IBOutlet UITextField *ju_textField;
@property (strong, nonatomic)  NSMutableArray *ju_arrMessage;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"zhu";
    UITableViewController *vc = [[UITableViewController alloc] init];
    vc.tableView=self.tableView;
    [self addChildViewController:vc];

    //ping
    self.pingTester = [[WHPingTester alloc] initWithHostName:@"www.baidu.com"];
    self.pingTester.delegate = self;
    [self.pingTester startPing];
    // Do any additional setup after loading the view, typically from a nib.
}
#pragma mark ping的回调
- (void) didPingSucccessWithTime:(float)time withError:(NSError *)error
{
    if(error){
        NSLog(@"网络有问题");
    }else{
        self.title = [[NSString stringWithFormat:@"%d", (int)time] stringByAppendingString:@"ms"];
    }
}

- (IBAction)shTouchLogin:(id)sender {
    //1.建立连接
    if (_inputStream.streamStatus==NSStreamStatusClosed||_inputStream.streamStatus==NSStreamStatusNotOpen) {
        NSString *host =@"192.168.8.2";

        int port =1234;

        //定义C语言输入输出流

        CFReadStreamRef readStream;

        CFWriteStreamRef writeStream;

        CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);

        //把C语言的输入输出流转化成OC对象

        _inputStream = (__bridge NSInputStream *)(readStream);

        _outputStream = (__bridge NSOutputStream *)(writeStream);

        //设置代理

        _inputStream.delegate=self;

        _outputStream.delegate=self;

        //把输入输入流添加到主运行循环

        //不添加主运行循环 代理有可能不工作

        [_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

        [_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

        //打开输入输出流

        [_inputStream open];

        [_outputStream open];
        [self.ju_btnLogin setTitle:@"退出" forState:UIControlStateNormal];
    }else{
        [_inputStream close];
        [_outputStream close];
        [self.ju_btnLogin setTitle:@"登录" forState:UIControlStateNormal];
    }


}
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{

    NSLog(@"%@",[NSThread currentThread]);

    //NSStreamEventOpenCompleted = 1UL << 0,//输入输出流打开完成//NSStreamEventHasBytesAvailable = 1UL << 1,//有字节可读//NSStreamEventHasSpaceAvailable = 1UL << 2,//可以发放字节//NSStreamEventErrorOccurred = 1UL << 3,//连接出现错误//NSStreamEventEndEncountered = 1UL << 4//连接结束

    switch(eventCode) {

        case NSStreamEventOpenCompleted:
        {
            NSLog(@"输入输出流打开完成");
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //登录的指令11
                NSString *loginStr =@"name:zhu";
                //把Str转成NSData
                NSData *data =[loginStr dataUsingEncoding:NSUTF8StringEncoding];

                [_outputStream write:data.bytes maxLength:data.length];
            });

        }


            break;

        case NSStreamEventHasBytesAvailable:

            NSLog(@"有字节可读");

            [self readData];

            break;

        case NSStreamEventHasSpaceAvailable:

            NSLog(@"可以发送字节");

            break;

        case NSStreamEventErrorOccurred:
            [_inputStream close];
            [_outputStream close];
            NSLog(@"连接出现错误");

            break;

        case NSStreamEventEndEncountered:

            NSLog(@"连接结束");

            //关闭输入输出流

            [_inputStream close];

            [_outputStream close];

            //从主运行循环移除

            [_inputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

            [_outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

            break;

        default:

            break;

    }
}
#pragma mark 读了服务器返回的数据

-(void)readData{

    //建立一个缓冲区 可以放1024个字节

    char buf[1024];

    //返回实际装的字节数

    NSInteger len = [_inputStream read:buf maxLength:sizeof(buf)];

    //把字节数组转化成字符串

    //    NSData *data =[NSData dataWithBytes:buf length:len];

    //从服务器接收到的数据

    NSString *recStr =[NSString stringWithCString:buf encoding:NSUTF8StringEncoding];

    NSLog(@"%@",recStr);
    [self juReloadData:recStr];
    //    [self reloadDataWithText:recStr];

}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    
    //发送的指令11
    NSString *loginStr =[NSString stringWithFormat:@"to:tian*%@",textField.text];
    //把Str转成NSData
    NSData *data =[loginStr dataUsingEncoding:NSUTF8StringEncoding];

    [_outputStream write:data.bytes maxLength:data.length];
    [self juReloadData:loginStr];
    textField.text =nil;
    return YES;
}
-(void)juReloadData:(NSString *)string{
    if (!_ju_arrMessage) {
        _ju_arrMessage=[NSMutableArray array];
    }
    [_ju_arrMessage addObject:string];
    [self.tableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath { 
    static NSString *CellIdentifier=@"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.text=_ju_arrMessage[indexPath.row];
    cell.textLabel.numberOfLines=0;
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return _ju_arrMessage.count;
}
@end
